package com.huawei.roma.setting;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private SeekBar volumeSeekBar = null;
    private AudioManager audioManager = null;

    private int REQUEST_CODE = 4;

    private int REQUEST_MICROPHONE = 8;


    private SeekBar seek_bar_brightness;
    private SeekBar seek_bar_volume;

    private TextView seekbar_progress_brightness;
    private TextView seekbar_progress_volume;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        findViewById(R.id.wifi_switcher).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wifiSwitcher();
            }
        });

        findViewById(R.id.bluetooth_switcher).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchBluetooth();
            }
        });

        findViewById(R.id.microphone_switcher).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchMicrophone();
            }
        });



        findViewById(R.id.screenshot_switcher).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                screenShot();
            }
        });

        findViewById(R.id.setting_switcher).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                settingPage();
            }
        });

        findViewById(R.id.power_off).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                powerOff();
            }
        });

        volumeSeekBar = findViewById(R.id.volume_seek_bar);
        volumeControls();


        seek_bar_brightness = findViewById(R.id.seek_bar_brightness);
        seekbar_progress_brightness = findViewById(R.id.seekbar_progress_brightness);
        seek_bar_brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                seekbar_progress_brightness.setText(progress+"%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        seek_bar_volume = findViewById(R.id.seek_bar_volume);
        seekbar_progress_volume = findViewById(R.id.seekbar_progress_volume);
        seek_bar_volume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                seekbar_progress_volume.setText(progress+"%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


    }

    private void switchBluetooth() {
        enableBluetoothAdapter();
    }

    private void enableBluetoothAdapter() {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        this.startActivityForResult(enableBtIntent,REQUEST_CODE);
    }

    private void switchMicrophone() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.RECORD_AUDIO},REQUEST_MICROPHONE);
        }
    }

    // https://stackoverflow.com/questions/2661536/how-to-programmatically-take-a-screenshot-on-android
    private void screenShot() {

        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

        try {
            // image naming and path  to include sd card  appending name you choose for file
            String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

            // create bitmap screen capture
            View v1 = getWindow().getDecorView().getRootView();
            v1.setDrawingCacheEnabled(true);
            Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
            v1.setDrawingCacheEnabled(false);

            File imageFile = new File(mPath);

            FileOutputStream outputStream = new FileOutputStream(imageFile);
            int quality = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();

            openScreenshot(imageFile);
        } catch (Throwable e) {
            // Several error may come out with file handling or DOM
            e.printStackTrace();
        }
    }

    private void openScreenshot(File imageFile) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(imageFile);
        intent.setDataAndType(uri, "image/*");
        startActivity(intent);
    }

    private void settingPage() {
        startActivityForResult(new Intent(Settings.ACTION_SETTINGS),0);
    }

    private void powerOff() {
        Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
//        intent.putExtra("android.intent.extra.KEY_CONFIRM", true);
        intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }



    private void wifiSwitcher() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(false);
        }else{
            wifiManager.setWifiEnabled(true);
        }
    }


    //https://stackoverflow.com/questions/10134338/using-seekbar-to-control-volume-in-android
    private void volumeControls()
    {
        try
        {
            audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            volumeSeekBar.setMax(audioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
            volumeSeekBar.setProgress(audioManager
                    .getStreamVolume(AudioManager.STREAM_MUSIC));


            volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
            {
                @Override
                public void onStopTrackingTouch(SeekBar arg0)
                {
                }

                @Override
                public void onStartTrackingTouch(SeekBar arg0)
                {
                }

                @Override
                public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
                {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                            progress, 0);
                }
            });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == REQUEST_CODE) {
            if (Activity.RESULT_OK == resultCode) {

            }else{

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}